import { Logger } from "../utils/Logger";
import { WebSocketClient } from "./WebSocketClient";
import { Config } from "../../config/Config";
import { ServerConfig } from "../../config/ServerConfig";
import { ServerManager } from "../../server/ServerManager";
import { SocketClientReqManager } from "./SocketClientReqManager";

export class WebSocketClientManager {

    public static instance: WebSocketClientManager = new WebSocketClientManager();


    private onlyId: number = 0;

    private webSocketClientMap: Map<string, WebSocketClient> = new Map<string, WebSocketClient>()

    public getWebSocketClientByServerConfig(serverConfig: ServerConfig) {
        let client: WebSocketClient;
        if (this.webSocketClientMap.has(serverConfig.getInternalWsUrl())) {
            client = this.webSocketClientMap.get(serverConfig.getInternalWsUrl())
        } else {
            client = this.createSocketClientByServerConfig(serverConfig)
            SocketClientReqManager.instance.req_server_internal_Login(serverConfig)
        }
        return client
    }

    public createSocketClientByServerConfig(serverConfig: ServerConfig) {
        let url: string = serverConfig.getInternalWsUrl()
        let webSocketClient: WebSocketClient = this.createSocketClient(url);
        this.webSocketClientMap.set(url, webSocketClient)
        return webSocketClient
    }

    public createSocketClient(url: string): WebSocketClient {
        this.onlyId++;
        let webSocketClient: WebSocketClient = new WebSocketClient();
        webSocketClient.init(url, this.onlyId);
        return webSocketClient;
    }

    public destoyWebSocketClient(webSocketClient: WebSocketClient) {
        this.webSocketClientMap.delete(webSocketClient.url)
        webSocketClient.close();
        webSocketClient.destroy();
        webSocketClient = null;
    }

}